package com.core.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;


public class RequestParams
        extends HashMap <String, String[]> {

	/**
     * 
     */
	private static final long serialVersionUID = 1L;



	public static RequestParams paramsFromRequest ( HttpServletRequest request ) {

		if ( request == null ) {
			return null;
		}

		@SuppressWarnings("unchecked") Map <String, String[]> map = request.getParameterMap();

		RequestParams result = new RequestParams();
		result.putAll(map);
		return result;
	}



	public String[] arrayForKey ( String key ) {

		return this.get(key);
	}



	public String stringAtIndexForKey ( int index,
	                                    String key ) {

		String[] array = this.arrayForKey(key);
		if ( array == null ) {
			return null;
		}
		String result = null;
		try {
			result = array[index];
		} catch ( ArrayIndexOutOfBoundsException e ) {
			result = null;
		}

		return result;
	}



	public Integer integerAtIndexForKey ( int index,
	                                      String key ) {

		String stringResult = this.stringAtIndexForKey(index, key);
		if ( stringResult == null ) {
			return null;
		}
		Integer result = null;
		try {
			result = Integer.parseInt(stringResult);
		} catch ( NumberFormatException e ) {
			result = null;
		}
		return result;
	}



	public Date dateAtIndexForKeyWithFormat ( int index,
	                                          String key,
	                                          String format ) {

		String stringResult = this.stringAtIndexForKey(index, key);
		if ( stringResult == null ) {
			return null;
		}

		Date result = null;
		try {
			DateFormat dateFormat = new SimpleDateFormat(format);
			Calendar cal = dateFormat.getCalendar();
			cal.setLenient(false);
			dateFormat.setCalendar(cal);
			result = dateFormat.parse(stringResult);

		} catch ( ParseException e ) {
			result = null;
		}
		return result;
	}
}
